import { createRouter, createWebHistory } from 'vue-router'

import home from '@/views/home.vue';
import AdminEbook from '@/views/admin/admin-ebook.vue';
import AdminUser from '@/views/admin/admin-user.vue';
import AdminCategory from '@/views/admin/admin-category.vue';
import AdminDoc from '@/views/admin/admin-doc.vue';
import about from '@/views/about.vue';
import Doc from '@/views/doc.vue';
import store from "../store/index.js";
import {Tool} from "../util/tool.ts";

const routes = [
  {
    path: '/',
    name: 'home',
    component: home
  },
  {
    path: '/admin/user',
    name: 'AdminUser',
    component: AdminUser,
    meta:{
       loginRequire: true
    }
  },
  {
    path: '/admin/ebook',
    name: 'AdminEbook',
    component: AdminEbook,
    meta:{
      loginRequire: true
    }
  },
  {
    path: '/admin/category',
    name: 'AdminCategory',
    component: AdminCategory,
    meta:{
      loginRequire: true
    }
  },
  {
    path: '/admin/doc',
    name: 'AdminDoc',
    component: AdminDoc,
    meta:{
      loginRequire: true
    }
  },
  {
    path: '/doc',
    name: 'Doc',
    component: Doc
  },
  {
    path: '/about',
    name: 'about',
    component: about
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 判断是否要校验登录
  if (to.matched.some((item) =>{
      console.log(item, "是否需要校验登录: ", item.meta.loginRequire);
      return item.meta.loginRequire;
  })){
     const user = store.state.loginUser;
     if (Tool.isEmpty(user)){
       console.log("用户未登录");
       next('/');
     } else {
       next();
     }
  } else {
      next();
  };

})

export default router
